package com.iot.ic.service;


import com.iot.ic.common.Constant;
import com.iot.ic.common.Options;
import com.iot.ic.dao.LocationMapper;
import com.iot.ic.httpclient.util.BaiduAddressInfo;
import com.iot.ic.model.Device;
import com.iot.ic.model.Location;
import com.iot.ic.model.TeamInfo;
import com.iot.ic.model.TeamLocation;
import com.iot.ic.tcp.model.Point;
import com.iot.ic.utils.DatetimeUtil;
import com.iot.ic.utils.LngAndLatUtil;
import com.iot.ic.utils.OkHttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiuge on 2017/7/10.
 */
@Service
public class LocationServiceImpl implements LocationService {

    @Autowired
    private LocationMapper locationMapper;

    @Autowired
    private DeviceService deviceService;
    
    @Autowired
    private TeamService teamService;
    
    @Autowired
    private TeamLocationService teamLocationService;

    private static Map<String,Point>pointMap=new HashMap<>();
    
    private static Map<String,TeamLocation>teamLocationMap = new HashMap<>();

    Logger logger= LoggerFactory.getLogger(LocationServiceImpl.class);


    @Override
    public Integer addLocation(Location location) {
        Device device = deviceService.getDeviceByName(location.getDeviceName());
        if (device.getDeviceState() == Options.Close.getCode()) {
        	device.setDeviceState(Options.Open.getCode());
        	Device newDevice = new Device();
        	newDevice.setDeviceId(device.getDeviceId());
        	newDevice.setDeviceState(Options.Open.getCode());
        	deviceService.updateDeviceState(newDevice);
        }
        location.setDeviceId(device.getDeviceId());
        location.setTeamId(device.getTeamId());
        location.setUpdateTime(new Date());
        int result = locationMapper.insertSelective(location);
        if (device.getTeamId() != null && (device.getTeamState() == Options.Normal.getCode()|| device.getTeamState() == Options.Pause.getCode())) {
        	 Point point = new Point();
             point.setDirection((int)(double)(location.getAngle()));
             point.setLatitude(location.getLat());
             point.setLongitude(location.getLng());
             point.setEntity_name(String.valueOf(device.getTeamId()));//"test01");
             point.setLoc_time(location.getCreateTime()/1000);//new Date().getTime() / 1000
             Point lastPoint=pointMap.get(point.getEntity_name());
             if ((lastPoint==null)||((!point.getLoc_time().equals(lastPoint.getLoc_time())) && (point.getLoc_time() > lastPoint.getLoc_time()))) {//百度鹰眼系统中同一个时间戳只有第一次上传的位置有效，所以每个时间戳最好只上传一个位置
             	 if (location.getLat() != 0 && location.getLng() != 0){
             		boolean postResult = OkHttpUtil.postRequest(point, Constant.ADD_TRACK_URL);
                    if (postResult)
                        logger.info("鹰眼轨迹上传成功" + point);
                    else
                        logger.info("鹰眼轨迹上传失败" + point);
                    
             	    if (postResult) {
             	    	TeamInfo team = teamService.getTeam(device.getTeamId());
                  		Map<String,String> baiduLoctionMap = LngAndLatUtil.gpsCodes2BaiduCodes(location.getLat(), location.getLng());
                  		String latitudeBaidu = baiduLoctionMap.get("lat");
                  		String longitudeBaidu = baiduLoctionMap.get("lng");
                  		BaiduAddressInfo baiduAddressInfo = LngAndLatUtil.LngAndLat2City(Double.parseDouble(longitudeBaidu), Double.parseDouble(latitudeBaidu));
                  		String address = (String) baiduAddressInfo.getResult().get("formatted_address");
                  		TeamLocation lastTeamLocation = teamLocationMap.get(point.getEntity_name());
                  		String lastLocationTime = null;
                  		String newLocationTime = null;
                  		if (lastTeamLocation != null) {
                  			lastLocationTime = DatetimeUtil.DateToString(lastTeamLocation.getLocationTime(), null);
                      	    newLocationTime = DatetimeUtil.DateToString(new Date(location.getCreateTime()), null);
                  		}
                  		if ((lastTeamLocation==null)||(!lastLocationTime.equals(newLocationTime))) {
                  				
                  			TeamLocation teamLocation = new TeamLocation();
                      		teamLocation.setPosition(address);
                      		teamLocation.setLatitude(Double.parseDouble(latitudeBaidu));
                      		teamLocation.setLongitude(Double.parseDouble(longitudeBaidu));
                      		teamLocation.setTeamId(device.getTeamId());
                      		teamLocation.setLocationTime(new Date(location.getCreateTime()));
                      		teamLocation.setDelFlag(0);
                      		teamLocation.setTeamName(team.getTeamName());
                      		teamLocation.setTeamState(team.getTeamState());
                      		teamLocationService.addLocationHistory(teamLocation);
                      		teamLocationMap.put(point.getEntity_name(),teamLocation);
                  		}	
             	    }
             	 }  	
             }
             pointMap.put(point.getEntity_name(),point);
        }
        return result;
    }


}
